import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, LoggerService } from "@nestjs/common";
import { HttpAdapterHost } from "@nestjs/core";
import * as requestIp from "request-ip";
import { QueryFailedError } from "typeorm";

@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  constructor(
    private readonly logger: LoggerService,
    private readonly httpAdapterHost: HttpAdapterHost
  ) {}
  catch(exception: HttpException, host: ArgumentsHost) {
    console.log("🚀 ~ AllExceptionFilter ~ exception:", exception)
    const { httpAdapter } = this.httpAdapterHost;
    const ctx = host.switchToHttp();
    // 请求 响应对象
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    // http 状态码
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    let msg:string = exception['response'] || 'Internal Server Error'
    // 加入异常错误逻辑
    msg = exception.message;
    if (exception instanceof QueryFailedError){
      // msg = exception.message;
      if (exception.driverError.errno === 1062){
        msg = '唯一索引冲突'
      }
    }
    const responseBody = {
      headers: request.headers,
      query: request.query,
      body: request.body,
      params: request.params,
      timestamp: new Date().toISOString(),
      ip: requestIp.getClientIp(request),
      exception: exception['name'],
      error: {
        message: msg,
      }
    }

    this.logger.error('[HttpExceptionFilter]',responseBody);
    httpAdapter.reply(response, responseBody, status);
    // const message = exception.message;

    // // 记录日志
    // this.logger.error(exception.message, exception.stack)

    // response.status(status).json({
    //   code: status,
    //   timestamp: new Date().toISOString(),
    //   path: request.url,
    //   method: request.method,
    //   message: message,
    // });
    // throw new Error('HttpExceptionFilter');
  }
}
